package com.xian.im.message.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.xian.im.common.utils.bussiness.GroupContextUtil;
import com.xian.im.message.model.RabbitMsg;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-02-01 15:38
 */
@Slf4j
@Component
public class XimGroupConsumer implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        String body = new String(message.getBody());
        try {
            RabbitMsg msg = JSONObject.parseObject(body,RabbitMsg.class);
            ChannelGroup groupChannel = GroupContextUtil.getGroupChannel(msg.getId());
            groupChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg.getResponse())));
            //log.info("mq群组消息 {}",body);
        }catch (JSONException e){
            log.error("json 转换异常{}, {}",body,e.getMessage());
        }catch (Exception e){
            log.error("消息消费失败 {} 错误信息 {}",body,e.getMessage());
        }
    }
}
